package dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.JdbcUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BaseDao {
    private QueryRunner queryRunner = new QueryRunner();

    /**
     * 更新数据
     * @param sql
     * @param args
     * @return 如果返回-1，表示执行失败
     */
    public int update(String sql,Object... args) throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        return queryRunner.update(connection,sql,args);
    }

    public <T> T queryForOne(Class<T> type,String sql, Object... args) throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        return queryRunner.query(connection,sql,new BeanHandler<T>(type),args);
    }

    public <T> List<T> queryForList(Class<T> type, String sql, Object... args) throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        return queryRunner.query(connection,sql, new BeanListHandler<T>(type),args);
    }

}
